#!/usr/bin/env python2
# -*- coding: utf-8 -*-

# Copyright (c) 2011 Alexandre Défossez
# This file is part of HINAPT.
#
# HINAPT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# HINAPT is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with HINAPT.  If not, see <http://www.gnu.org/licenses/>.

"""
Exporte le code source en LaTeX.
"""

TEMPLATE = r"""
\documentclass[a4paper]{article}
\usepackage{lmodern}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{fancyvrb}
\usepackage{color}
\usepackage{geometry}

\geometry{
a4paper,
body={160mm,250mm},
left=30mm,top=25mm,
headheight=7mm,headsep=4mm,
marginparsep=4mm,
marginparwidth=27mm}


%(defs)s
\begin{document}
%(codes)s

\end{document}
"""

import glob
import os
from subprocess import check_call
from pygments.formatters import LatexFormatter
from pygments.lexers import CppLexer, PythonLexer
from pygments import highlight


formatter = None
lexer =  CppLexer(encoding="utf-8")


l = glob.glob("*.hpp")
l.extend(glob.glob("*.cpp"))
l.sort()

s = []
for i in l:
    print "Adding", i
    f = "\n".join(open(i).readlines()[16:])
    formatter = LatexFormatter(linenos=True,
    verboptions='baselinestretch=0.4,\
    frame=topline,fontsize=\small,label=%s'%(i.replace("_",r"\_")))
    s.append(highlight(f, lexer, formatter))

l = glob.glob("*.py")
l.extend(glob.glob("scripts/img_getter/*.py"))
lexer = PythonLexer(encoding="utf8")

for i in l:
    print "Adding", i
    f = "\n".join(open(i).readlines()[18:])
    formatter = LatexFormatter(linenos=True,
    verboptions='baselinestretch=0.4,\
    frame=topline,fontsize=\small,label=%s'%(i.replace("_",r"\_")))
    s.append(highlight(f, lexer, formatter))

d = TEMPLATE%{'defs':formatter.get_style_defs(),'codes':'\n'.join(s)}

open("export/export.tex", "w").write(d.encode("utf-8"))

print "Exporting to pdf ...",
os.chdir("export")
check_call(["pdflatex", "export.tex"])
print "[OK]"
